﻿using LiteBlog.Common.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace LiteBlog.Infrastructure
{
    public class DraftPostModelBinder : IModelBinder
    {
        private DefaultModelBinder _binder = new DefaultModelBinder();

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            // Categories, OldCategories do not bind well by the default binder
            // Ditto with Tags, OldTags
            // and Documents
            var post = (DraftPost)_binder.BindModel(controllerContext, bindingContext);
            var modelState = bindingContext.ModelState;
            if (modelState.ContainsKey("Categories"))
                modelState["Categories"].Errors.Clear();
            if (modelState.ContainsKey("Documents"))
                modelState["Documents"].Errors.Clear();
            if (modelState.ContainsKey("OldCategories"))
                modelState["OldCategories"].Errors.Clear();
            if (modelState.ContainsKey("Tags"))
                modelState["Tags"].Errors.Clear();
            if (modelState.ContainsKey("OldTags"))
                modelState["OldTags"].Errors.Clear();
            var request = controllerContext.HttpContext.Request;
            var categories = request.Form.Get("Categories");
            var serializer = new JavaScriptSerializer();
            post.Categories = (List<Category>)serializer.Deserialize(categories, typeof(List<Category>));
            var oldCategories = request.Form.Get("OldCategories");
            post.OldCategories = (List<Category>)serializer.Deserialize(oldCategories, typeof(List<Category>));
            var tags = request.Form.Get("Tags");
            post.Tags = (List<Tag>)serializer.Deserialize(tags, typeof(List<Tag>));
            var oldTags = request.Form.Get("OldTags");
            post.OldTags = (List<Tag>)serializer.Deserialize(oldTags, typeof(List<Tag>));
            var attachments = request.Form.Get("Documents");
            post.Documents = (List<Document>)serializer.Deserialize(attachments, typeof(List<Document>));
            return post;
        }
    }
}